import axios from "axios";
import {getStore, setStore} from "js-utils";
import {Validate} from "js-utils/validate";
import {Message} from "element-ui";
import JSONbig from 'json-bigint';
import {BASE_URL} from "@/assets/const/constData";
import router from '@/router';
import eventBus from "@/config/eventBus";
// axios.defaults.baseURL = 'http://127.0.0.1:8199';
// 动态设置 baseURL
// const setBaseURL = () => {
//     const serverIp = getStore('guard-ip',1) || '127.0.0.1';
//     axios.defaults.baseURL = `http://${serverIp}:80`;
// };
//
// // 设置初始 baseURL
// setBaseURL();
const instance = axios.create({
    timeout: 60000,
    baseURL: BASE_URL,
    transformResponse: [function (data) {
        try {
            // 如果转换成功则返回转换的数据结果
            const json = JSONbig({
                storeAsString: true
            })
            return json.parse(data)
        } catch (err) {
            // 如果转换失败，则包装为统一数据格式并返回
            return {
                data
            }
        }
    }]
});
export default instance;
instance.interceptors.request.use(config => {
    let { url, method } = config;
    method = (method || 'get').toLowerCase();
    const dataKey = method === 'get' ? 'params' : 'data';

    if (!config[dataKey]) {
        config[dataKey] = {};
    }

    const requestData = config[dataKey];
    if (config.url.indexOf('/login-for-backend') === -1) {
        config.headers = config.headers || {};
        config.headers['coffee-token'] = 'Bearer ' + getStore('token', true);
    }
    // 确保字符串参数被正确处理
    Object.keys(requestData).forEach(key => {
        if (typeof requestData[key] === 'string') {
            requestData[key] = requestData[key].trim();
        }
    });

    return config;
}, error => {
    return Promise.reject(error);
});
// 导出一个函数，用于在 IP 地址改变时重新设置 baseURL
// export const updateBaseURL = () => {
//     setBaseURL();
// };

instance.interceptors.response.use(
    response => {
        const { code, msg } = response.data;
        if (code === 200) {
            return response.data;
        }else if (code === 401 ) {
            setStore('token', null, true);
            Message({
                message: '登录已过期，请重新登录',
                type: 'error'
            });
            eventBus.$emit('clear-token'); // 触发全局事件
        }

        Message({
            message: msg,
            type: 'error'
        });
        return Promise.resolve(response.data);
    },
    error => {
        if (!error.response) {
            Message({
                message: '网络错误，请检查网络连接',
                type: 'error'
            });
            return Promise.reject(error);
        }
        const { status, data } = error.response;
        const msg = data?.msg || '请求失败，请稍后重试';
        const code = data?.code || status;
        // 401 状态码处理
        if (status === 401 || code === 401) {
            setStore('token', null, true);
            Message({
                message: '登录已过期，请重新登录',
                type: 'error'
            });
            // 跳转到登录页
            eventBus.$emit('clear-token'); // 触发全局事件
        }
        // 其他错误状态处理
        else {
            Message({
                message: code === 300 ? msg : '请求失败，请稍后重试',
                type: code === 300 ? 'warning' : 'error'
            });
        }
        return Promise.reject(error);
    }
);


// export default axios;